package main

import (
    "fmt"
    "net"
    "time"
)

func startSlave() {
    conn, err := net.Dial("tcp", config.SlaveAddr)
    if err != nil {
        fmt.Println("Error connecting to slave:", err)
        return
    }
    defer conn.Close()

    fmt.Println("Connected to slave on", config.SlaveAddr)

    for {
        // 模拟事件采集
        event := collectEvent()
        if event != "" {
            sendIEC104Message(conn, IEC104Message{Type: "E", Data: event, AuthKey: generateAuthKey(event, config.AuthKey)})
        }
        // 模拟数据采集
        data := collectData()
        sendIEC104Message(conn, IEC104Message{Type: "C", Data: data, AuthKey: generateAuthKey(data, config.AuthKey)})
        
        // 新增时钟同步逻辑
        syncClock(conn)
        
        // 接收并处理遥控命令
        handleRemoteControl(conn)

        // 新增：处理文件传输请求
        handleFileTransferRequest(conn)

        // 新增：处理单个事件
        handleSingleEvent(conn)

        // 新增：处理保护设备启动事件
        handleProtectionDeviceStartEvent(conn)

        // 新增：处理保护设备电路信息
        handleCircuitInfo(conn)

        time.Sleep(5 * time.Second)
    }
}

// 新增函数：处理保护设备电路信息
func handleCircuitInfo(conn net.Conn) {
    circuitInfo := collectCircuitInfo()
    if circuitInfo != "" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Protection device circuit info detected: %s\n", timestamp, circuitInfo)
        sendIEC104Message(conn, IEC104Message{Type: "CIRCUIT_INFO", Data: circuitInfo, AuthKey: generateAuthKey(circuitInfo, config.AuthKey)})
    }
}

// 新增函数：采集保护设备电路信息
func collectCircuitInfo() string {
    timestamp := time.Now().Format(time.RFC3339) // 记录时间戳
    // 假设电路信息在每分钟的第30秒触发
    now := time.Now()
    if now.Second() == 30 {
        return fmt.Sprintf("[%s] Circuit information at %02d:%02d: Voltage=220V, Current=5A", timestamp, now.Hour(), now.Minute())
    }
    return ""
}

// 新增函数：处理保护设备启动事件
func handleProtectionDeviceStartEvent(conn net.Conn) {
    event := collectProtectionDeviceStartEvent()
    if event != "" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Protection device start event detected: %s\n", timestamp, event)
        sendIEC104Message(conn, IEC104Message{Type: "PROTECT_START", Data: event, AuthKey: generateAuthKey(event, config.AuthKey)})
    }
}

// 新增函数：采集保护设备启动事件
func collectProtectionDeviceStartEvent() string {
    timestamp := time.Now().Format(time.RFC3339) // 记录时间戳
    // 假设保护设备启动事件在每分钟的第10秒触发
    now := time.Now()
    if now.Second() == 10 {
        return fmt.Sprintf("[%s] Protection device started at %02d:%02d", timestamp, now.Hour(), now.Minute())
    }
    return ""
}

// 新增函数：处理单个事件
func handleSingleEvent(conn net.Conn) {
    event := collectSingleEvent()
    if event != "" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Single event detected: %s\n", timestamp, event)
        sendIEC104Message(conn, IEC104Message{Type: "EVENT", Data: event, AuthKey: generateAuthKey(event, config.AuthKey)})
    }
}

// 新增函数：采集单个事件
func collectSingleEvent() string {
    timestamp := time.Now().Format(time.RFC3339) // 新增：记录时间戳
    if time.Now().UnixNano()%10 == 0 {
        return fmt.Sprintf("[%s] Single Event-%d", timestamp, time.Now().UnixNano()%100)
    }
    return ""
}

// 新增函数：处理文件传输请求
func handleFileTransferRequest(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving file transfer request:", err)
        return
    }

    if message.Type == "FILE" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received file transfer request for %s\n", timestamp, message.Data)
        // 模拟文件传输过程
        sendFileData(conn, message.Data)
    }
}

// 新增函数：发送文件数据
func sendFileData(conn net.Conn, fileName string) {
    timestamp := time.Now().Format(time.RFC3339)
    message := fmt.Sprintf("File data for %s at %s", fileName, timestamp)
    sendIEC104Message(conn, IEC104Message{Type: "DATA", Data: message, AuthKey: generateAuthKey(message, config.AuthKey)})
    fmt.Println("File data sent:", message)
}

// 新增函数：处理复位进程命令
func handleResetProcess(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving reset process message:", err)
        return
    }

    if message.Type == "RESET" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received reset process command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的复位进程响应逻辑
        sendIEC104Message(conn, IEC104Message{Type: "RESET", Data: "00", AuthKey: generateAuthKey("00", config.AuthKey)})
    }
}

// 新增函数：处理时钟同步命令
func handleClockSynchronization(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving clock synchronization message:", err)
        return
    }

    if message.Type == "T" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received clock synchronization command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的时钟同步响应逻辑
        sendIEC104Message(conn, IEC104Message{Type: "T", Data: "00", AuthKey: generateAuthKey("00", config.AuthKey)})
    }
}

// 新增函数：响应电能脉冲召唤命令
func respondToPulseInterrogation(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving pulse interrogation message:", err)
        return
    }

    if message.Type == "PULSE" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received pulse interrogation command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的电能脉冲召唤响应逻辑
        sendIEC104Message(conn, IEC104Message{Type: "PULSE", Data: "00", AuthKey: generateAuthKey("00", config.AuthKey)})
    }
}

// 新增函数：响应总召唤命令
func respondToGeneralInterrogation(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving general interrogation message:", err)
        return
    }

    if message.Type == "G" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received general interrogation command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的总召唤响应逻辑
        sendIEC104Message(conn, IEC104Message{Type: "G", Data: "00", AuthKey: generateAuthKey("00", config.AuthKey)})
    }
}

// 新增函数：处理遥控命令
func handleRemoteControl(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving remote control message:", err)
        return
    }

    if message.Type == "R" {
        timestamp := time.Now().Format(time.RFC3339) // 新增：记录时间戳
        fmt.Printf("[%s] Received remote control command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的遥控命令处理逻辑
        sendIEC104Message(conn, IEC104Message{Type: "A", Data: "02", AuthKey: generateAuthKey("02", config.AuthKey)})
    }
}

func collectEvent() string {
    timestamp := time.Now().Format(time.RFC3339) // 新增：记录时间戳
    if time.Now().UnixNano()%10 == 0 {
        return fmt.Sprintf("[%s] Event-%d", timestamp, time.Now().UnixNano()%100)
    }
    return ""
}

func collectData() string {
    timestamp := time.Now().Format(time.RFC3339) // 新增：记录时间戳
    return fmt.Sprintf("[%s] %d", timestamp, time.Now().UnixNano()%100)
}

func syncClock(conn net.Conn) {
    currentTime := time.Now().Format(time.RFC3339)
    timestamp := time.Now().Format(time.RFC3339) // 新增：记录时间戳
    sendIEC104Message(conn, IEC104Message{Type: "T", Data: currentTime, AuthKey: generateAuthKey(currentTime, config.AuthKey)})
    fmt.Println("[%s] Clock synchronization request sent. Current time:", timestamp, currentTime)
}

// 新增函数：处理带时标CP56Time2a的测试命令
func handleTimestampedTestCommand(conn net.Conn) {
    message, err := receiveIEC104Message(conn)
    if err != nil {
        fmt.Println("Error receiving timestamped test command:", err)
        return
    }

    if message.Type == "TS" {
        timestamp := time.Now().Format(time.RFC3339)
        fmt.Printf("[%s] Received timestamped test command: %s\n", timestamp, message.Data)
        // 这里可以添加实际的带时标测试命令响应逻辑
        sendIEC104Message(conn, IEC104Message{Type: "TS", Data: "00", AuthKey: generateAuthKey("00", config.AuthKey)})
    }
}
